package com.toweave.starter.activity;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.toweave.starter.R;
import com.toweave.starter.beans.JsonAttributes;
import com.toweave.starter.beans.TestBean;
import com.toweave.starter.beans.UserBean;
import com.toweave.starter.utils.FastJsonUtil;
import com.toweave.starter.utils.RequestUtil;
import com.toweave.starter.utils.ResponseCallBack;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class RequestActivity extends AppCompatActivity implements View.OnClickListener {

  private ActivityResultLauncher<Intent> register;
  private OkHttpClient okHttpClient;
  private TextView tv_response_data;
  private UserBean user;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_request);

    TextView btn_request = findViewById(R.id.btn_request);
    btn_request.setOnClickListener(this);

    TextView btn_request_from_remote = findViewById(R.id.btn_request_from_remote);
    btn_request_from_remote.setOnClickListener(this);

    tv_response_data = findViewById(R.id.tv_response_data);
    btn_request_from_remote.setOnClickListener(this);

    register = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
      @Override
      public void onActivityResult(ActivityResult result) {
        if (result.getResultCode() == RESULT_OK) {
          Intent intent = result.getData();
          Bundle bundle = intent.getExtras();
          String response_time = bundle.getString("response_time");
          String response_content = bundle.getString("response_content");
          String desc = String.format("response_time: %s, response_content: %s", response_time, response_content);
          TextView tv_request_desc = findViewById(R.id.tv_request_desc);
          tv_request_desc.setText(desc);
        }
      }
    });
  }

  @Override
  public void onClick(View v) {
    int id = v.getId();
    Intent intent = new Intent(RequestActivity.this, ResponseActivity.class);
    // 发送消息
    Bundle bundle = new Bundle();
    ArrayList<UserBean> users = null;
    if (id == R.id.btn_request) {
      bundle.putString("request_time", "1_2_3");
      bundle.putString("request_content", "A_B_C");

      String[] request_str_list = {"A1", "B1", "C1"};
      bundle.putStringArray("request_str_list", request_str_list);

      // 将 ArrayList 传递到下一个 Activity
      ArrayList<String> strArrayList = new ArrayList<>();
      strArrayList.add("item1");
      strArrayList.add("item2");
      bundle.putStringArrayList("request_str_array_list", strArrayList);

      // 创建一个 UserBean Serializable
      user = new UserBean(0, "name1", "code1");
      bundle.putSerializable("request_user_serializable", user);

      // // 创建一个 ArrayList Serializable
      users = new ArrayList<>();
      // 添加 UserBean 到 ArrayList
      users.add(new UserBean(1, "User1", "Code1"));
      users.add(new UserBean(2, "User2", "Code2"));
      users.add(new UserBean(3, "User3", "Code3"));
      bundle.putParcelableArrayList("userBeanArrayListKey", users);

      intent.putExtras(bundle);
      register.launch(intent);
    } else if (id == R.id.btn_request_from_remote) {
      Object object = null;
      // object.put("test", "test");
      // String params = FastJsonUtil.ObjectToJsonString(users);
      JsonAttributes obj = new JsonAttributes();
      obj.setAttribute("name", "John Doe");
      obj.setAttribute("age", 30);
      obj.setAttribute("hobbies", new String[]{"Reading", "Hiking", "Coding"});
      Log.i("-liz-DynamicAttributes:", obj.toString());
      // String params = FastJsonUtil.ObjectToJsonString(obj);
      user = new UserBean(9, "name9", "code9");
      String params = FastJsonUtil.ObjectToJsonString(user);
      // users = new ArrayList<>();
      // // 添加 UserBean 到 ArrayList
      // users.add(new UserBean(1, "User1", "Code1"));
      // users.add(new UserBean(2, "User2", "Code2"));
      // users.add(new UserBean(3, "User3", "Code3"));
      // String params = FastJsonUtil.ObjectToJsonString(users);
      Log.i("-liz-params:", params);
      // Loading loadingDialog = new Loading(this);
      // loadingDialog.show();

      RequestUtil.postAsync(this, "https://reqres.in/api/user", params, new ResponseCallBack() {
        @Override
        public void onResponse(TestBean response) {
          // loadingDialog.hide();
          if (response != null) {
            Log.i("-liz-response:", String.valueOf(response));
            tv_response_data.setText(response.getCreatedAt());
          }
          // runOnUiThread(new Runnable() {
          //   @Override
          //   public void run() {
          //     tv_response_data.setText(response);
          //   }
          // });
        }

        @Override
        public void onFailure(IOException e) {
          Log.i("-liz-response IOException:", e.toString());
          // loadingDialog.hide();
        }
      });
      // okHttpClient = new OkHttpClient.Builder().build();
      // testGet();
    }
    // end
  }

  private void testGet() {
    Request request = new Request.Builder()
        .url("https://reqres.in/api/users")
        .get()
        .build();
    // 同步
    new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          Response response = okHttpClient.newCall(request).execute();
          String s = response.body().string();
          Log.i("-liz-response:", s);
          runOnUiThread(new Runnable() {
            @Override
            public void run() {
              tv_response_data.setText(s);
            }
          });
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }).start();
  }
}